package com.hxzy.controller.admin.employee;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.annotates.RequiredRole;
import com.hxzy.common.annotates.RequiredRootRole;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.MarketThreadLocalUtil;
import com.hxzy.controller.admin.employee.req.*;
import com.hxzy.controller.admin.employee.resp.EmployeeEditResp;
import com.hxzy.controller.admin.employee.resp.EmployeeResp;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.entity.Employee;
import com.hxzy.mapstruct.EmployeeMapStruct;
import com.hxzy.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.error.Mark;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * 查询 使用 Get方式     @GetMapping
 * 新增 使用 POST方式    @PostMapping
 * 修改 使用put方式      @PutMapping
 * 删除 使用delete方式   @DeleteMapping
 */
@Api(tags = "后台-员工Api")
@RestController
@RequestMapping(value = "/api/employee")
public class EmployeeController extends BaseController {

    @Autowired
    private EmployeeService  employeeService;

    /**
     * 分页查询
     * @param req
     * @return
     */
    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "分页查询")
    @GetMapping(value ="/data")
    public R<PageInfo<EmployeeResp>>  search(EmployeeSearchReq req){
        //1、开启分页
        super.startPage(req);

        //2、查询条件
        List<EmployeeResp>  list=this.employeeService.search(req);

        //3、返回结果
        return super.buildPageInfo(list);
    }

    @RequiredRootRole
    @ApiOperation(value = "新增员工")
    @PostMapping
    public R addData(@RequestBody @Valid EmployeeAddReq req){

        boolean result =this.employeeService.addData(req);

        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "账号是否存在")
    @GetMapping(value = "/account/exists/{account}")
    public R  accountExists(@PathVariable(value = "account") String account){
        if(StrUtil.isBlank(account)){
            throw new ServiceException(AckCode.SYSTEM_PARAM_FAIL);
        }

        boolean result=this.employeeService.accountExists(account);
        //前端必须接收正常返回结果
        return result? R.okHasData(AckCode.EXISTS_VALUE_ACCOUNT.getMsg()): R.ok();
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<EmployeeEditResp> findById(@PathVariable(value = "id") Long id){
        if(Objects.isNull(id) || id<=MarketConstants.ACCOUNT_NORMAL){
            throw new ServiceException(AckCode.SYSTEM_PARAM_FAIL);
        }

        Employee db = this.employeeService.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        return R.okHasData(EmployeeMapStruct.INSTANCE.convert(db));
    }


    /**
     * 管理员可以更改，但是超管不能调这个接口
     * @param req
     * @return
     */
    @ApiOperation(value = "更新员工信息")
    @PutMapping
    public R updateData(@RequestBody @Valid EmployeeEditReq req){
        AdminLoginResp adminLoginResp = MarketThreadLocalUtil.ADMIN_THREAD_LOCAL.get();
        if(! (MarketConstants.ACCOUNT_ADMIN_TYPE.equals(adminLoginResp.getPermissions())  &&  MarketConstants.ACCOUNT_ROOT!= adminLoginResp.getRoot()) ){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS);
        }
        boolean result=this.employeeService.updateData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @RequiredRootRole
    @ApiOperation(value = "超级管理更新员工信息")
    @PutMapping(value = "/update")
    public R superMapUpdateData(@RequestBody @Valid EmployeeSuperManEditReq req){

        boolean result=this.employeeService.updateData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @RequiredRootRole
    @ApiOperation(value = "更改账户状态")
    @PutMapping(value = "/change/status")
    public R changeStatus(@RequestBody @Valid EmployeeStatusReq req){
        boolean result=this.employeeService.changeStatus(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download")
    public void download(@RequestBody  EmployeeSearchReq req,  HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<EmployeeResp> respList = this.employeeService.search(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), EmployeeResp.class).sheet("员工列表").doWrite(respList);
    }

    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download/choice")
    public void downloadIds(@RequestBody  EmployeeExportIdsReq req,  HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<EmployeeResp> respList = this.employeeService.exportExcel(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), EmployeeResp.class).sheet("员工列表").doWrite(respList);
    }

}
